package com.leetcode.LC_MED;

public class LC416_2 {
    public boolean canPartition(int[] nums) {

        int len = nums.length;
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        if (sum % 2 == 1) {//如果和为奇数则直接退出
            return false;
        } else {
            sum /= 2;
        }

        boolean[][] dp = new boolean[len][sum + 1];

        if (nums[0] <= sum) {
            dp[0][nums[0]] = true;
        }
        for (int i = 1; i < len; i++) {
            for (int j = 0; j <= sum; j++) {
                dp[i][j] = dp[i - 1][j];

                if (nums[i] == j) {
                    dp[i][j] = true;
                    continue;
                }
                if (nums[i] < j) {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]];
                }
            }
        }
        return dp[len - 1][sum];
    }

}
